import 'dart:async';

import 'package:get/get.dart';
import 'package:kong/domain/repository/api_repository.dart';
import 'package:kong/domain/repository/local_storage_repository.dart';

// Implement SplashController
class SplashController extends GetxController {
  final LocalRepositoryInterface local;
  final ApiRepositoryInterface api;

  SplashController({
    this.local,
    this.api,
  });

  String targetPage = '';
  Timer _splashTimer;
  final _duration = Duration(seconds: 1);

  final countDown = 5.obs;

  @override
  void onReady() {
    validateSession();
    super.onReady();
  }

  // 路由切换没有触发
  @override
  void onClose() {
    // 组件销毁时(跳转离开)判断Timer是否仍然处于激活状态，是则取消
    if (_splashTimer.isActive) {
      _splashTimer.cancel();
    }
  }

  void validateSession() async {
    final token = await local.getToken();
    print(token);
    if (token != null) {
      final user = await api.getUserFromToken(token);
      await local.setUser(user);
      targetPage = '/home';
    } else {
      targetPage = '/login';
    }
    splashTimeInterval();
  }

  Future<Timer> splashTimeInterval() async {
    _splashTimer = Timer.periodic(_duration, (timer) {
      countDown.value--;
      // 定时器一定要记得设置取消条件，手动取消
      if (countDown.value <= 0) {
        timer.cancel();
        Get.offNamed(targetPage);
      }
    });
    return _splashTimer;
  }

  // 延时 - 不能设置跳过时间
  // Future<Timer> splashTimeOut() async {
  //   return Timer(
  //     this._duration,
  //     () {
  //       // Navigator.pushNamed(context, '/guide');
  //       // Navigator.pushReplacementNamed(context, '/guide');
  //     },
  //   );
  // }
}
